//
// Created by 文道江 on 16/1/13.
// Copyright (c) 2016 文道江. All rights reserved.
//

#import "VideoPlayerViewController.h"


@implementation VideoPlayerViewController {
    MPMoviePlayerViewController *_playerViewController;
    MPMoviePlayerController *_player;
}

- (instancetype)initWithUrl:(NSURL *)url {
    self = [super init];
    if (self) {
        self.url = url;
    }

    return self;
}

+ (instancetype)controllerWithUrl:(NSURL *)url {
    return [[self alloc] initWithUrl:url];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = self.autoPlay;
    if (!self.autoPlay) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"使用" style:UIBarButtonItemStylePlain target:self action:@selector(pressDoneButton:)];
    }
    self.view.backgroundColor = [UIColor blackColor];

    _playerViewController = [[MPMoviePlayerViewController alloc] initWithContentURL:_url];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayBackDidFinish:)
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
                                               object:[_playerViewController moviePlayer]];
    // add to view
    [self.view addSubview:_playerViewController.view];

    // play movie
    _player = [_playerViewController moviePlayer];
    _player.controlStyle = MPMovieControlStyleDefault;
    _player.shouldAutoplay = YES;

}

- (void)viewDidAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden = NO;
    self.title = @"视频播放";

    if (self.autoPlay && _player) {
        [_player play];
    }
}

- (void)viewDidDisappear:(BOOL)animated{
    [_player pause];
}

- (void)viewWillDisappear:(BOOL)animated {
    self.navigationController.navigationBarHidden = YES;
    [_player stop];
    _player = nil;
    _playerViewController = nil;
}

- (void)moviePlayBackDidFinish:(MPMoviePlayerViewController *)playerViewController{
    //播放完成
}

- (void)pressDoneButton:(UIBarButtonItem *)button{
    if (self.payDelegate && [self.payDelegate respondsToSelector:@selector(pressDone:)]){
        [self.payDelegate pressDone:_url];
    }
    [self pressBackButton:nil];
}

- (void)pressBackButton:(UIButton *)button {
    if (self.navigationController) {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }

    if (self.presentingViewController) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

@end